package com.lwc.filter;

import jdk.nashorn.internal.objects.Global;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;


import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取所有请求头
        HttpHeaders headers = exchange.getRequest().getHeaders();
        //获取token
        String token = headers.getFirst("x-token");
        if (null == token) {
            //没有token 禁止访问
            //获取响应对象
            ServerHttpResponse response = exchange.getResponse();
            //设置响应状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//未授权
            //设置响应头
            response.getHeaders().add("Content-Type", "application/json");
            DataBuffer buffer = response.bufferFactory().wrap("{\"code\":0,\"msg\":\"没有token，无权访问\"}".getBytes());
            return response.writeWith(Mono.just(buffer));
        }
//放行
        return chain.filter(exchange);


    }


    //过滤器的优先级  值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }


}
